<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Leetcode 题解 - 树 | Zhang Shuo'blog</title><meta name="keywords" content="Leetcode题解"><meta name="author" content="Zhang Shuo"><meta name="copyright" content="Zhang Shuo"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Leetcode 题解 - 树  Leetcode 题解 - 树 递归 1. 树的高度 2. 平衡树 3. 两节点的最长路径 4. 翻转树 5. 归并两棵树 6. 判断路径和是否等于一个数 7. 统计路径和等于一个数的路径数量 8. 子树 9. 树的对称 10. 最小路径 11. 统计左叶子节点的和 12. 相同节点值的最大路径长度 13. 间隔遍历 14. 找出二叉树中第二小的节点   层次遍历">
<meta property="og:type" content="article">
<meta property="og:title" content="Leetcode 题解 - 树">
<meta property="og:url" content="https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E6%A0%91/index.html">
<meta property="og:site_name" content="Zhang Shuo&#39;blog">
<meta property="og:description" content="Leetcode 题解 - 树  Leetcode 题解 - 树 递归 1. 树的高度 2. 平衡树 3. 两节点的最长路径 4. 翻转树 5. 归并两棵树 6. 判断路径和是否等于一个数 7. 统计路径和等于一个数的路径数量 8. 子树 9. 树的对称 10. 最小路径 11. 统计左叶子节点的和 12. 相同节点值的最大路径长度 13. 间隔遍历 14. 找出二叉树中第二小的节点   层次遍历">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://zhang-shuo-fr.gitee.io/hexo3/img/13.jpg">
<meta property="article:published_time" content="2021-12-06T09:36:00.000Z">
<meta property="article:modified_time" content="2021-12-10T12:57:38.860Z">
<meta property="article:author" content="Zhang Shuo">
<meta property="article:tag" content="Leetcode题解">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zhang-shuo-fr.gitee.io/hexo3/img/13.jpg"><link rel="shortcut icon" href="/hexo3/img/mao_tou_xiang.jpg"><link rel="canonical" href="https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E6%A0%91/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="manifest" href="/hexo3/pwa/manifest.json"/><link rel="apple-touch-icon" sizes="180x180" href="/hexo3/pwa/apple-touch-icon.png"/><link rel="icon" type="image/png" sizes="32x32" href="/hexo3/pwa/32.png"/><link rel="icon" type="image/png" sizes="16x16" href="/hexo3/pwa/16.png"/><link rel="mask-icon" href="/hexo3/pwa/safari-pinned-tab.svg" color="#5bbad5"/><link rel="stylesheet" href="/hexo3/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web&amp;display=swap" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/hexo3/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Leetcode 题解 - 树',
  isPost: true,
  isHome: false,
  isHighlightShrink: undefined,
  isToc: true,
  postUpdate: '2021-12-10 20:57:38'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    document.addEventListener('pjax:complete', detectApple)})(window)</script><style type="text/css">#toggle-sidebar {left:100px}</style><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/hexo3/img/mao_tou_xiang.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/hexo3/archives/"><div class="headline">文章</div><div class="length-num">176</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/hexo3/tags/"><div class="headline">标签</div><div class="length-num">45</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/hexo3/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/hexo3/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 小窝</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/hexo3/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/hexo3/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/hexo3/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/hexo3/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/hexo3/img/13.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/hexo3/">Zhang Shuo'blog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/hexo3/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 小窝</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/hexo3/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/hexo3/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/hexo3/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/hexo3/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Leetcode 题解 - 树</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-12-06T09:36:00.000Z" title="发表于 2021-12-06 17:36:00">2021-12-06</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-12-10T12:57:38.860Z" title="更新于 2021-12-10 20:57:38">2021-12-10</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/hexo3/categories/Leetcode%E9%A2%98%E8%A7%A3/">Leetcode题解</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>22分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Leetcode 题解 - 树"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Leetcode-题解-树"><a href="#Leetcode-题解-树" class="headerlink" title="Leetcode 题解 - 树"></a>Leetcode 题解 - 树</h1><!-- GFM-TOC -->
<ul>
<li><a href="#leetcode-%E9%A2%98%E8%A7%A3---%E6%A0%91">Leetcode 题解 - 树</a><ul>
<li><a href="#%E9%80%92%E5%BD%92">递归</a><ul>
<li><a href="#1-%E6%A0%91%E7%9A%84%E9%AB%98%E5%BA%A6">1. 树的高度</a></li>
<li><a href="#2-%E5%B9%B3%E8%A1%A1%E6%A0%91">2. 平衡树</a></li>
<li><a href="#3-%E4%B8%A4%E8%8A%82%E7%82%B9%E7%9A%84%E6%9C%80%E9%95%BF%E8%B7%AF%E5%BE%84">3. 两节点的最长路径</a></li>
<li><a href="#4-%E7%BF%BB%E8%BD%AC%E6%A0%91">4. 翻转树</a></li>
<li><a href="#5-%E5%BD%92%E5%B9%B6%E4%B8%A4%E6%A3%B5%E6%A0%91">5. 归并两棵树</a></li>
<li><a href="#6-%E5%88%A4%E6%96%AD%E8%B7%AF%E5%BE%84%E5%92%8C%E6%98%AF%E5%90%A6%E7%AD%89%E4%BA%8E%E4%B8%80%E4%B8%AA%E6%95%B0">6. 判断路径和是否等于一个数</a></li>
<li><a href="#7-%E7%BB%9F%E8%AE%A1%E8%B7%AF%E5%BE%84%E5%92%8C%E7%AD%89%E4%BA%8E%E4%B8%80%E4%B8%AA%E6%95%B0%E7%9A%84%E8%B7%AF%E5%BE%84%E6%95%B0%E9%87%8F">7. 统计路径和等于一个数的路径数量</a></li>
<li><a href="#8-%E5%AD%90%E6%A0%91">8. 子树</a></li>
<li><a href="#9-%E6%A0%91%E7%9A%84%E5%AF%B9%E7%A7%B0">9. 树的对称</a></li>
<li><a href="#10-%E6%9C%80%E5%B0%8F%E8%B7%AF%E5%BE%84">10. 最小路径</a></li>
<li><a href="#11-%E7%BB%9F%E8%AE%A1%E5%B7%A6%E5%8F%B6%E5%AD%90%E8%8A%82%E7%82%B9%E7%9A%84%E5%92%8C">11. 统计左叶子节点的和</a></li>
<li><a href="#12-%E7%9B%B8%E5%90%8C%E8%8A%82%E7%82%B9%E5%80%BC%E7%9A%84%E6%9C%80%E5%A4%A7%E8%B7%AF%E5%BE%84%E9%95%BF%E5%BA%A6">12. 相同节点值的最大路径长度</a></li>
<li><a href="#13-%E9%97%B4%E9%9A%94%E9%81%8D%E5%8E%86">13. 间隔遍历</a></li>
<li><a href="#14-%E6%89%BE%E5%87%BA%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%AD%E7%AC%AC%E4%BA%8C%E5%B0%8F%E7%9A%84%E8%8A%82%E7%82%B9">14. 找出二叉树中第二小的节点</a></li>
</ul>
</li>
<li><a href="#%E5%B1%82%E6%AC%A1%E9%81%8D%E5%8E%86">层次遍历</a><ul>
<li><a href="#1-%E4%B8%80%E6%A3%B5%E6%A0%91%E6%AF%8F%E5%B1%82%E8%8A%82%E7%82%B9%E7%9A%84%E5%B9%B3%E5%9D%87%E6%95%B0">1. 一棵树每层节点的平均数</a></li>
<li><a href="#2-%E5%BE%97%E5%88%B0%E5%B7%A6%E4%B8%8B%E8%A7%92%E7%9A%84%E8%8A%82%E7%82%B9">2. 得到左下角的节点</a></li>
</ul>
</li>
<li><a href="#%E5%89%8D%E4%B8%AD%E5%90%8E%E5%BA%8F%E9%81%8D%E5%8E%86">前中后序遍历</a><ul>
<li><a href="#1-%E9%9D%9E%E9%80%92%E5%BD%92%E5%AE%9E%E7%8E%B0%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%89%8D%E5%BA%8F%E9%81%8D%E5%8E%86">1. 非递归实现二叉树的前序遍历</a></li>
<li><a href="#2-%E9%9D%9E%E9%80%92%E5%BD%92%E5%AE%9E%E7%8E%B0%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%90%8E%E5%BA%8F%E9%81%8D%E5%8E%86">2. 非递归实现二叉树的后序遍历</a></li>
<li><a href="#3-%E9%9D%9E%E9%80%92%E5%BD%92%E5%AE%9E%E7%8E%B0%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E4%B8%AD%E5%BA%8F%E9%81%8D%E5%8E%86">3. 非递归实现二叉树的中序遍历</a></li>
</ul>
</li>
<li><a href="#bst">BST</a><ul>
<li><a href="#1-%E4%BF%AE%E5%89%AA%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91">1. 修剪二叉查找树</a></li>
<li><a href="#2-%E5%AF%BB%E6%89%BE%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91%E7%9A%84%E7%AC%AC-k-%E4%B8%AA%E5%85%83%E7%B4%A0">2. 寻找二叉查找树的第 k 个元素</a></li>
<li><a href="#3-%E6%8A%8A%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91%E6%AF%8F%E4%B8%AA%E8%8A%82%E7%82%B9%E7%9A%84%E5%80%BC%E9%83%BD%E5%8A%A0%E4%B8%8A%E6%AF%94%E5%AE%83%E5%A4%A7%E7%9A%84%E8%8A%82%E7%82%B9%E7%9A%84%E5%80%BC">3. 把二叉查找树每个节点的值都加上比它大的节点的值</a></li>
<li><a href="#4-%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91%E7%9A%84%E6%9C%80%E8%BF%91%E5%85%AC%E5%85%B1%E7%A5%96%E5%85%88">4. 二叉查找树的最近公共祖先</a></li>
<li><a href="#5-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E8%BF%91%E5%85%AC%E5%85%B1%E7%A5%96%E5%85%88">5. 二叉树的最近公共祖先</a></li>
<li><a href="#6-%E4%BB%8E%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84%E4%B8%AD%E6%9E%84%E9%80%A0%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91">6. 从有序数组中构造二叉查找树</a></li>
<li><a href="#7-%E6%A0%B9%E6%8D%AE%E6%9C%89%E5%BA%8F%E9%93%BE%E8%A1%A8%E6%9E%84%E9%80%A0%E5%B9%B3%E8%A1%A1%E7%9A%84%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91">7. 根据有序链表构造平衡的二叉查找树</a></li>
<li><a href="#8-%E5%9C%A8%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91%E4%B8%AD%E5%AF%BB%E6%89%BE%E4%B8%A4%E4%B8%AA%E8%8A%82%E7%82%B9%EF%BC%8C%E4%BD%BF%E5%AE%83%E4%BB%AC%E7%9A%84%E5%92%8C%E4%B8%BA%E4%B8%80%E4%B8%AA%E7%BB%99%E5%AE%9A%E5%80%BC">8. 在二叉查找树中寻找两个节点，使它们的和为一个给定值</a></li>
<li><a href="#9-%E5%9C%A8%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91%E4%B8%AD%E6%9F%A5%E6%89%BE%E4%B8%A4%E4%B8%AA%E8%8A%82%E7%82%B9%E4%B9%8B%E5%B7%AE%E7%9A%84%E6%9C%80%E5%B0%8F%E7%BB%9D%E5%AF%B9%E5%80%BC">9. 在二叉查找树中查找两个节点之差的最小绝对值</a></li>
<li><a href="#10-%E5%AF%BB%E6%89%BE%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91%E4%B8%AD%E5%87%BA%E7%8E%B0%E6%AC%A1%E6%95%B0%E6%9C%80%E5%A4%9A%E7%9A%84%E5%80%BC">10. 寻找二叉查找树中出现次数最多的值</a></li>
</ul>
</li>
<li><a href="#trie">Trie</a><ul>
<li><a href="#1-%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA-trie">1. 实现一个 Trie</a></li>
<li><a href="#2-%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA-trie%EF%BC%8C%E7%94%A8%E6%9D%A5%E6%B1%82%E5%89%8D%E7%BC%80%E5%92%8C">2. 实现一个 Trie，用来求前缀和</a><!-- GFM-TOC --></li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="递归"><a href="#递归" class="headerlink" title="递归"></a>递归</h2><p>一棵树要么是空树，要么有两个指针，每个指针指向一棵树。树是一种递归结构，很多树的问题可以使用递归来处理。</p>
<h3 id="1-树的高度"><a href="#1-树的高度" class="headerlink" title="1. 树的高度"></a>1. 树的高度</h3><p>104. Maximum Depth of Binary Tree (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/maximum-depth-of-binary-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/description/">力扣</a></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">maxDepth</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">return</span> Math.max(maxDepth(root.left), maxDepth(root.right)) + <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="2-平衡树"><a href="#2-平衡树" class="headerlink" title="2. 平衡树"></a>2. 平衡树</h3><p>110. Balanced Binary Tree (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/balanced-binary-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/balanced-binary-tree/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">  3</span><br><span class="line"> / \</span><br><span class="line">9  20</span><br><span class="line">  /  \</span><br><span class="line"> 15   7</span><br></pre></td></tr></table></figure>

<p>平衡树左右子树高度差都小于等于 1</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">boolean</span> result = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isBalanced</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    maxDepth(root);</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">maxDepth</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> l = maxDepth(root.left);</span><br><span class="line">    <span class="keyword">int</span> r = maxDepth(root.right);</span><br><span class="line">    <span class="keyword">if</span> (Math.abs(l - r) &gt; <span class="number">1</span>) result = <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">1</span> + Math.max(l, r);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-两节点的最长路径"><a href="#3-两节点的最长路径" class="headerlink" title="3. 两节点的最长路径"></a>3. 两节点的最长路径</h3><p>543. Diameter of Binary Tree (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/diameter-of-binary-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/diameter-of-binary-tree/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input:</span><br><span class="line"></span><br><span class="line">         1</span><br><span class="line">        / \</span><br><span class="line">       2  3</span><br><span class="line">      / \</span><br><span class="line">     4   5</span><br><span class="line"></span><br><span class="line">Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> max = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">diameterOfBinaryTree</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    depth(root);</span><br><span class="line">    <span class="keyword">return</span> max;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">depth</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> leftDepth = depth(root.left);</span><br><span class="line">    <span class="keyword">int</span> rightDepth = depth(root.right);</span><br><span class="line">    max = Math.max(max, leftDepth + rightDepth);</span><br><span class="line">    <span class="keyword">return</span> Math.max(leftDepth, rightDepth) + <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4-翻转树"><a href="#4-翻转树" class="headerlink" title="4. 翻转树"></a>4. 翻转树</h3><p>226. Invert Binary Tree (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/invert-binary-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/invert-binary-tree/description/">力扣</a></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> TreeNode <span class="title">invertTree</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    TreeNode left = root.left;  <span class="comment">// 后面的操作会改变 left 指针，因此先保存下来</span></span><br><span class="line">    root.left = invertTree(root.right);</span><br><span class="line">    root.right = invertTree(left);</span><br><span class="line">    <span class="keyword">return</span> root;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-归并两棵树"><a href="#5-归并两棵树" class="headerlink" title="5. 归并两棵树"></a>5. 归并两棵树</h3><p>617. Merge Two Binary Trees (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/merge-two-binary-trees/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/merge-two-binary-trees/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input:</span><br><span class="line">       Tree 1                     Tree 2</span><br><span class="line">          1                         2</span><br><span class="line">         / \                       / \</span><br><span class="line">        3   2                     1   3</span><br><span class="line">       /                           \   \</span><br><span class="line">      5                             4   7</span><br><span class="line"></span><br><span class="line">Output:</span><br><span class="line">         3</span><br><span class="line">        / \</span><br><span class="line">       4   5</span><br><span class="line">      / \   \</span><br><span class="line">     5   4   7</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> TreeNode <span class="title">mergeTrees</span><span class="params">(TreeNode t1, TreeNode t2)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (t1 == <span class="keyword">null</span> &amp;&amp; t2 == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">if</span> (t1 == <span class="keyword">null</span>) <span class="keyword">return</span> t2;</span><br><span class="line">    <span class="keyword">if</span> (t2 == <span class="keyword">null</span>) <span class="keyword">return</span> t1;</span><br><span class="line">    TreeNode root = <span class="keyword">new</span> TreeNode(t1.val + t2.val);</span><br><span class="line">    root.left = mergeTrees(t1.left, t2.left);</span><br><span class="line">    root.right = mergeTrees(t1.right, t2.right);</span><br><span class="line">    <span class="keyword">return</span> root;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="6-判断路径和是否等于一个数"><a href="#6-判断路径和是否等于一个数" class="headerlink" title="6. 判断路径和是否等于一个数"></a>6. 判断路径和是否等于一个数</h3><p>Leetcdoe : 112. Path Sum (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/path-sum/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/path-sum/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Given the below binary tree and sum = 22,</span><br><span class="line"></span><br><span class="line">              5</span><br><span class="line">             / \</span><br><span class="line">            4   8</span><br><span class="line">           /   / \</span><br><span class="line">          11  13  4</span><br><span class="line">         /  \      \</span><br><span class="line">        7    2      1</span><br><span class="line"></span><br><span class="line">return true, as there exist a root-to-leaf path 5-&gt;4-&gt;11-&gt;2 which sum is 22.</span><br></pre></td></tr></table></figure>

<p>路径和定义为从 root 到 leaf 的所有节点的和。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasPathSum</span><span class="params">(TreeNode root, <span class="keyword">int</span> sum)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">if</span> (root.left == <span class="keyword">null</span> &amp;&amp; root.right == <span class="keyword">null</span> &amp;&amp; root.val == sum) <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    <span class="keyword">return</span> hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="7-统计路径和等于一个数的路径数量"><a href="#7-统计路径和等于一个数的路径数量" class="headerlink" title="7. 统计路径和等于一个数的路径数量"></a>7. 统计路径和等于一个数的路径数量</h3><p>437. Path Sum III (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/path-sum-iii/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/path-sum-iii/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8</span><br><span class="line"></span><br><span class="line">      10</span><br><span class="line">     /  \</span><br><span class="line">    5   -3</span><br><span class="line">   / \    \</span><br><span class="line">  3   2   11</span><br><span class="line"> / \   \</span><br><span class="line">3  -2   1</span><br><span class="line"></span><br><span class="line">Return 3. The paths that sum to 8 are:</span><br><span class="line"></span><br><span class="line">1.  5 -&gt; 3</span><br><span class="line">2.  5 -&gt; 2 -&gt; 1</span><br><span class="line">3. -3 -&gt; 11</span><br></pre></td></tr></table></figure>

<p>路径不一定以 root 开头，也不一定以 leaf 结尾，但是必须连续。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">pathSum</span><span class="params">(TreeNode root, <span class="keyword">int</span> sum)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> ret = pathSumStartWithRoot(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">pathSumStartWithRoot</span><span class="params">(TreeNode root, <span class="keyword">int</span> sum)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> ret = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span> (root.val == sum) ret++;</span><br><span class="line">    ret += pathSumStartWithRoot(root.left, sum - root.val) + pathSumStartWithRoot(root.right, sum - root.val);</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="8-子树"><a href="#8-子树" class="headerlink" title="8. 子树"></a>8. 子树</h3><p>572. Subtree of Another Tree (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/subtree-of-another-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/subtree-of-another-tree/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Given tree s:</span><br><span class="line">     3</span><br><span class="line">    / \</span><br><span class="line">   4   5</span><br><span class="line">  / \</span><br><span class="line"> 1   2</span><br><span class="line"></span><br><span class="line">Given tree t:</span><br><span class="line">   4</span><br><span class="line">  / \</span><br><span class="line"> 1   2</span><br><span class="line"></span><br><span class="line">Return true, because t has the same structure and node values with a subtree of s.</span><br><span class="line"></span><br><span class="line">Given tree s:</span><br><span class="line"></span><br><span class="line">     3</span><br><span class="line">    / \</span><br><span class="line">   4   5</span><br><span class="line">  / \</span><br><span class="line"> 1   2</span><br><span class="line">    /</span><br><span class="line">   0</span><br><span class="line"></span><br><span class="line">Given tree t:</span><br><span class="line">   4</span><br><span class="line">  / \</span><br><span class="line"> 1   2</span><br><span class="line"></span><br><span class="line">Return false.</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isSubtree</span><span class="params">(TreeNode s, TreeNode t)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (s == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">return</span> isSubtreeWithRoot(s, t) || isSubtree(s.left, t) || isSubtree(s.right, t);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">isSubtreeWithRoot</span><span class="params">(TreeNode s, TreeNode t)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (t == <span class="keyword">null</span> &amp;&amp; s == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    <span class="keyword">if</span> (t == <span class="keyword">null</span> || s == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">if</span> (t.val != s.val) <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">return</span> isSubtreeWithRoot(s.left, t.left) &amp;&amp; isSubtreeWithRoot(s.right, t.right);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="9-树的对称"><a href="#9-树的对称" class="headerlink" title="9. 树的对称"></a>9. 树的对称</h3><p>101. Symmetric Tree (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/symmetric-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/symmetric-tree/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">    1</span><br><span class="line">   / \</span><br><span class="line">  2   2</span><br><span class="line"> / \ / \</span><br><span class="line">3  4 4  3</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isSymmetric</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    <span class="keyword">return</span> isSymmetric(root.left, root.right);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">isSymmetric</span><span class="params">(TreeNode t1, TreeNode t2)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (t1 == <span class="keyword">null</span> &amp;&amp; t2 == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    <span class="keyword">if</span> (t1 == <span class="keyword">null</span> || t2 == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">if</span> (t1.val != t2.val) <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">return</span> isSymmetric(t1.left, t2.right) &amp;&amp; isSymmetric(t1.right, t2.left);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="10-最小路径"><a href="#10-最小路径" class="headerlink" title="10. 最小路径"></a>10. 最小路径</h3><p>111. Minimum Depth of Binary Tree (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/minimum-depth-of-binary-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/description/">力扣</a></p>
<p>树的根节点到叶子节点的最小路径长度</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">minDepth</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> left = minDepth(root.left);</span><br><span class="line">    <span class="keyword">int</span> right = minDepth(root.right);</span><br><span class="line">    <span class="keyword">if</span> (left == <span class="number">0</span> || right == <span class="number">0</span>) <span class="keyword">return</span> left + right + <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">return</span> Math.min(left, right) + <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="11-统计左叶子节点的和"><a href="#11-统计左叶子节点的和" class="headerlink" title="11. 统计左叶子节点的和"></a>11. 统计左叶子节点的和</h3><p>404. Sum of Left Leaves (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/sum-of-left-leaves/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/sum-of-left-leaves/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">    3</span><br><span class="line">   / \</span><br><span class="line">  9  20</span><br><span class="line">    /  \</span><br><span class="line">   15   7</span><br><span class="line"></span><br><span class="line">There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">sumOfLeftLeaves</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span> (isLeaf(root.left)) <span class="keyword">return</span> root.left.val + sumOfLeftLeaves(root.right);</span><br><span class="line">    <span class="keyword">return</span> sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">isLeaf</span><span class="params">(TreeNode node)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (node == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">return</span> node.left == <span class="keyword">null</span> &amp;&amp; node.right == <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="12-相同节点值的最大路径长度"><a href="#12-相同节点值的最大路径长度" class="headerlink" title="12. 相同节点值的最大路径长度"></a>12. 相同节点值的最大路径长度</h3><p>687. Longest Univalue Path (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/longest-univalue-path/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/longest-univalue-path/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">             1</span><br><span class="line">            / \</span><br><span class="line">           4   5</span><br><span class="line">          / \   \</span><br><span class="line">         4   4   5</span><br><span class="line"></span><br><span class="line">Output : 2</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> path = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">longestUnivaluePath</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    dfs(root);</span><br><span class="line">    <span class="keyword">return</span> path;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">dfs</span><span class="params">(TreeNode root)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> left = dfs(root.left);</span><br><span class="line">    <span class="keyword">int</span> right = dfs(root.right);</span><br><span class="line">    <span class="keyword">int</span> leftPath = root.left != <span class="keyword">null</span> &amp;&amp; root.left.val == root.val ? left + <span class="number">1</span> : <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> rightPath = root.right != <span class="keyword">null</span> &amp;&amp; root.right.val == root.val ? right + <span class="number">1</span> : <span class="number">0</span>;</span><br><span class="line">    path = Math.max(path, leftPath + rightPath);</span><br><span class="line">    <span class="keyword">return</span> Math.max(leftPath, rightPath);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="13-间隔遍历"><a href="#13-间隔遍历" class="headerlink" title="13. 间隔遍历"></a>13. 间隔遍历</h3><p>337. House Robber III (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/house-robber-iii/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/house-robber-iii/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">     3</span><br><span class="line">    / \</span><br><span class="line">   2   3</span><br><span class="line">    \   \</span><br><span class="line">     3   1</span><br><span class="line">Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Map&lt;TreeNode, Integer&gt; cache = <span class="keyword">new</span> HashMap&lt;&gt;(); </span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">rob</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span> (cache.containsKey(root)) <span class="keyword">return</span> cache.get(root);</span><br><span class="line">    <span class="keyword">int</span> val1 = root.val;</span><br><span class="line">    <span class="keyword">if</span> (root.left != <span class="keyword">null</span>) val1 += rob(root.left.left) + rob(root.left.right);</span><br><span class="line">    <span class="keyword">if</span> (root.right != <span class="keyword">null</span>) val1 += rob(root.right.left) + rob(root.right.right);</span><br><span class="line">    <span class="keyword">int</span> val2 = rob(root.left) + rob(root.right);</span><br><span class="line">    <span class="keyword">int</span> res = Math.max(val1, val2);</span><br><span class="line">    cache.put(root, res);</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="14-找出二叉树中第二小的节点"><a href="#14-找出二叉树中第二小的节点" class="headerlink" title="14. 找出二叉树中第二小的节点"></a>14. 找出二叉树中第二小的节点</h3><p>671. Second Minimum Node In a Binary Tree (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input:</span><br><span class="line">   2</span><br><span class="line">  / \</span><br><span class="line"> 2   5</span><br><span class="line">    / \</span><br><span class="line">    5  7</span><br><span class="line"></span><br><span class="line">Output: 5</span><br></pre></td></tr></table></figure>

<p>一个节点要么具有 0 个或 2 个子节点，如果有子节点，那么根节点是最小的节点。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">findSecondMinimumValue</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">    <span class="keyword">if</span> (root.left == <span class="keyword">null</span> &amp;&amp; root.right == <span class="keyword">null</span>) <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">    <span class="keyword">int</span> leftVal = root.left.val;</span><br><span class="line">    <span class="keyword">int</span> rightVal = root.right.val;</span><br><span class="line">    <span class="keyword">if</span> (leftVal == root.val) leftVal = findSecondMinimumValue(root.left);</span><br><span class="line">    <span class="keyword">if</span> (rightVal == root.val) rightVal = findSecondMinimumValue(root.right);</span><br><span class="line">    <span class="keyword">if</span> (leftVal != -<span class="number">1</span> &amp;&amp; rightVal != -<span class="number">1</span>) <span class="keyword">return</span> Math.min(leftVal, rightVal);</span><br><span class="line">    <span class="keyword">if</span> (leftVal != -<span class="number">1</span>) <span class="keyword">return</span> leftVal;</span><br><span class="line">    <span class="keyword">return</span> rightVal;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="层次遍历"><a href="#层次遍历" class="headerlink" title="层次遍历"></a>层次遍历</h2><p>使用 BFS 进行层次遍历。不需要使用两个队列来分别存储当前层的节点和下一层的节点，因为在开始遍历一层的节点时，当前队列中的节点数就是当前层的节点数，只要控制遍历这么多节点数，就能保证这次遍历的都是当前层的节点。</p>
<h3 id="1-一棵树每层节点的平均数"><a href="#1-一棵树每层节点的平均数" class="headerlink" title="1. 一棵树每层节点的平均数"></a>1. 一棵树每层节点的平均数</h3><p>637. Average of Levels in Binary Tree (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/average-of-levels-in-binary-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/description/">力扣</a></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Double&gt; <span class="title">averageOfLevels</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    List&lt;Double&gt; ret = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span> ret;</span><br><span class="line">    Queue&lt;TreeNode&gt; queue = <span class="keyword">new</span> LinkedList&lt;&gt;();</span><br><span class="line">    queue.add(root);</span><br><span class="line">    <span class="keyword">while</span> (!queue.isEmpty()) &#123;</span><br><span class="line">        <span class="keyword">int</span> cnt = queue.size();</span><br><span class="line">        <span class="keyword">double</span> sum = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; cnt; i++) &#123;</span><br><span class="line">            TreeNode node = queue.poll();</span><br><span class="line">            sum += node.val;</span><br><span class="line">            <span class="keyword">if</span> (node.left != <span class="keyword">null</span>) queue.add(node.left);</span><br><span class="line">            <span class="keyword">if</span> (node.right != <span class="keyword">null</span>) queue.add(node.right);</span><br><span class="line">        &#125;</span><br><span class="line">        ret.add(sum / cnt);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="2-得到左下角的节点"><a href="#2-得到左下角的节点" class="headerlink" title="2. 得到左下角的节点"></a>2. 得到左下角的节点</h3><p>513. Find Bottom Left Tree Value (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/find-bottom-left-tree-value/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-bottom-left-tree-value/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input:</span><br><span class="line"></span><br><span class="line">        1</span><br><span class="line">       / \</span><br><span class="line">      2   3</span><br><span class="line">     /   / \</span><br><span class="line">    4   5   6</span><br><span class="line">       /</span><br><span class="line">      7</span><br><span class="line"></span><br><span class="line">Output:</span><br><span class="line">7</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">findBottomLeftValue</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    Queue&lt;TreeNode&gt; queue = <span class="keyword">new</span> LinkedList&lt;&gt;();</span><br><span class="line">    queue.add(root);</span><br><span class="line">    <span class="keyword">while</span> (!queue.isEmpty()) &#123;</span><br><span class="line">        root = queue.poll();</span><br><span class="line">        <span class="keyword">if</span> (root.right != <span class="keyword">null</span>) queue.add(root.right);</span><br><span class="line">        <span class="keyword">if</span> (root.left != <span class="keyword">null</span>) queue.add(root.left);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> root.val;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="前中后序遍历"><a href="#前中后序遍历" class="headerlink" title="前中后序遍历"></a>前中后序遍历</h2><figure class="highlight html"><table><tr><td class="code"><pre><span class="line">    1</span><br><span class="line">   / \</span><br><span class="line">  2   3</span><br><span class="line"> / \   \</span><br><span class="line">4   5   6</span><br></pre></td></tr></table></figure>

<ul>
<li>层次遍历顺序：[1 2 3 4 5 6]</li>
<li>前序遍历顺序：[1 2 4 5 3 6]</li>
<li>中序遍历顺序：[4 2 5 1 3 6]</li>
<li>后序遍历顺序：[4 5 2 6 3 1]</li>
</ul>
<p>层次遍历使用 BFS 实现，利用的就是 BFS 一层一层遍历的特性；而前序、中序、后序遍历利用了 DFS 实现。</p>
<p>前序、中序、后序遍只是在对节点访问的顺序有一点不同，其它都相同。</p>
<p>① 前序</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">dfs</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    visit(root);</span><br><span class="line">    dfs(root.left);</span><br><span class="line">    dfs(root.right);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>② 中序</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">dfs</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    dfs(root.left);</span><br><span class="line">    visit(root);</span><br><span class="line">    dfs(root.right);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>③ 后序</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">dfs</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    dfs(root.left);</span><br><span class="line">    dfs(root.right);</span><br><span class="line">    visit(root);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="1-非递归实现二叉树的前序遍历"><a href="#1-非递归实现二叉树的前序遍历" class="headerlink" title="1. 非递归实现二叉树的前序遍历"></a>1. 非递归实现二叉树的前序遍历</h3><p>144. Binary Tree Preorder Traversal (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/binary-tree-preorder-traversal/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/binary-tree-preorder-traversal/description/">力扣</a></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Integer&gt; <span class="title">preorderTraversal</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    List&lt;Integer&gt; ret = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    Stack&lt;TreeNode&gt; stack = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">    stack.push(root);</span><br><span class="line">    <span class="keyword">while</span> (!stack.isEmpty()) &#123;</span><br><span class="line">        TreeNode node = stack.pop();</span><br><span class="line">        <span class="keyword">if</span> (node == <span class="keyword">null</span>) <span class="keyword">continue</span>;</span><br><span class="line">        ret.add(node.val);</span><br><span class="line">        stack.push(node.right);  <span class="comment">// 先右后左，保证左子树先遍历</span></span><br><span class="line">        stack.push(node.left);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="2-非递归实现二叉树的后序遍历"><a href="#2-非递归实现二叉树的后序遍历" class="headerlink" title="2. 非递归实现二叉树的后序遍历"></a>2. 非递归实现二叉树的后序遍历</h3><p>145. Binary Tree Postorder Traversal (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/binary-tree-postorder-traversal/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/binary-tree-postorder-traversal/description/">力扣</a></p>
<p>前序遍历为 root -&gt; left -&gt; right，后序遍历为 left -&gt; right -&gt; root。可以修改前序遍历成为 root -&gt; right -&gt; left，那么这个顺序就和后序遍历正好相反。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Integer&gt; <span class="title">postorderTraversal</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    List&lt;Integer&gt; ret = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    Stack&lt;TreeNode&gt; stack = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">    stack.push(root);</span><br><span class="line">    <span class="keyword">while</span> (!stack.isEmpty()) &#123;</span><br><span class="line">        TreeNode node = stack.pop();</span><br><span class="line">        <span class="keyword">if</span> (node == <span class="keyword">null</span>) <span class="keyword">continue</span>;</span><br><span class="line">        ret.add(node.val);</span><br><span class="line">        stack.push(node.left);</span><br><span class="line">        stack.push(node.right);</span><br><span class="line">    &#125;</span><br><span class="line">    Collections.reverse(ret);</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-非递归实现二叉树的中序遍历"><a href="#3-非递归实现二叉树的中序遍历" class="headerlink" title="3. 非递归实现二叉树的中序遍历"></a>3. 非递归实现二叉树的中序遍历</h3><p>94. Binary Tree Inorder Traversal (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/binary-tree-inorder-traversal/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/binary-tree-inorder-traversal/description/">力扣</a></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Integer&gt; <span class="title">inorderTraversal</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    List&lt;Integer&gt; ret = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span> ret;</span><br><span class="line">    Stack&lt;TreeNode&gt; stack = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">    TreeNode cur = root;</span><br><span class="line">    <span class="keyword">while</span> (cur != <span class="keyword">null</span> || !stack.isEmpty()) &#123;</span><br><span class="line">        <span class="keyword">while</span> (cur != <span class="keyword">null</span>) &#123;</span><br><span class="line">            stack.push(cur);</span><br><span class="line">            cur = cur.left;</span><br><span class="line">        &#125;</span><br><span class="line">        TreeNode node = stack.pop();</span><br><span class="line">        ret.add(node.val);</span><br><span class="line">        cur = node.right;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="BST"><a href="#BST" class="headerlink" title="BST"></a>BST</h2><p>二叉查找树（BST）：根节点大于等于左子树所有节点，小于等于右子树所有节点。</p>
<p>二叉查找树中序遍历有序。</p>
<h3 id="1-修剪二叉查找树"><a href="#1-修剪二叉查找树" class="headerlink" title="1. 修剪二叉查找树"></a>1. 修剪二叉查找树</h3><p>669. Trim a Binary Search Tree (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/trim-a-binary-search-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/trim-a-binary-search-tree/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input:</span><br><span class="line"></span><br><span class="line">    3</span><br><span class="line">   / \</span><br><span class="line">  0   4</span><br><span class="line">   \</span><br><span class="line">    2</span><br><span class="line">   /</span><br><span class="line">  1</span><br><span class="line"></span><br><span class="line">  L = 1</span><br><span class="line">  R = 3</span><br><span class="line"></span><br><span class="line">Output:</span><br><span class="line"></span><br><span class="line">      3</span><br><span class="line">     /</span><br><span class="line">   2</span><br><span class="line">  /</span><br><span class="line"> 1</span><br></pre></td></tr></table></figure>

<p>题目描述：只保留值在 L ~ R 之间的节点</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> TreeNode <span class="title">trimBST</span><span class="params">(TreeNode root, <span class="keyword">int</span> L, <span class="keyword">int</span> R)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">if</span> (root.val &gt; R) <span class="keyword">return</span> trimBST(root.left, L, R);</span><br><span class="line">    <span class="keyword">if</span> (root.val &lt; L) <span class="keyword">return</span> trimBST(root.right, L, R);</span><br><span class="line">    root.left = trimBST(root.left, L, R);</span><br><span class="line">    root.right = trimBST(root.right, L, R);</span><br><span class="line">    <span class="keyword">return</span> root;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="2-寻找二叉查找树的第-k-个元素"><a href="#2-寻找二叉查找树的第-k-个元素" class="headerlink" title="2. 寻找二叉查找树的第 k 个元素"></a>2. 寻找二叉查找树的第 k 个元素</h3><p>230. Kth Smallest Element in a BST (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/description/">力扣</a></p>
<p>中序遍历解法：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> cnt = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> val;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">kthSmallest</span><span class="params">(TreeNode root, <span class="keyword">int</span> k)</span> </span>&#123;</span><br><span class="line">    inOrder(root, k);</span><br><span class="line">    <span class="keyword">return</span> val;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">inOrder</span><span class="params">(TreeNode node, <span class="keyword">int</span> k)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (node == <span class="keyword">null</span>) <span class="keyword">return</span>;</span><br><span class="line">    inOrder(node.left, k);</span><br><span class="line">    cnt++;</span><br><span class="line">    <span class="keyword">if</span> (cnt == k) &#123;</span><br><span class="line">        val = node.val;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    inOrder(node.right, k);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>递归解法：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">kthSmallest</span><span class="params">(TreeNode root, <span class="keyword">int</span> k)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> leftCnt = count(root.left);</span><br><span class="line">    <span class="keyword">if</span> (leftCnt == k - <span class="number">1</span>) <span class="keyword">return</span> root.val;</span><br><span class="line">    <span class="keyword">if</span> (leftCnt &gt; k - <span class="number">1</span>) <span class="keyword">return</span> kthSmallest(root.left, k);</span><br><span class="line">    <span class="keyword">return</span> kthSmallest(root.right, k - leftCnt - <span class="number">1</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">count</span><span class="params">(TreeNode node)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (node == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">1</span> + count(node.left) + count(node.right);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-把二叉查找树每个节点的值都加上比它大的节点的值"><a href="#3-把二叉查找树每个节点的值都加上比它大的节点的值" class="headerlink" title="3. 把二叉查找树每个节点的值都加上比它大的节点的值"></a>3. 把二叉查找树每个节点的值都加上比它大的节点的值</h3><p>Convert BST to Greater Tree (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/convert-bst-to-greater-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/convert-bst-to-greater-tree/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input: The root of a Binary Search Tree like this:</span><br><span class="line"></span><br><span class="line">              5</span><br><span class="line">            /   \</span><br><span class="line">           2     13</span><br><span class="line"></span><br><span class="line">Output: The root of a Greater Tree like this:</span><br><span class="line"></span><br><span class="line">             18</span><br><span class="line">            /   \</span><br><span class="line">          20     13</span><br></pre></td></tr></table></figure>

<p>先遍历右子树。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> sum = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> TreeNode <span class="title">convertBST</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    traver(root);</span><br><span class="line">    <span class="keyword">return</span> root;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">traver</span><span class="params">(TreeNode node)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (node == <span class="keyword">null</span>) <span class="keyword">return</span>;</span><br><span class="line">    traver(node.right);</span><br><span class="line">    sum += node.val;</span><br><span class="line">    node.val = sum;</span><br><span class="line">    traver(node.left);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4-二叉查找树的最近公共祖先"><a href="#4-二叉查找树的最近公共祖先" class="headerlink" title="4. 二叉查找树的最近公共祖先"></a>4. 二叉查找树的最近公共祖先</h3><p>235. Lowest Common Ancestor of a Binary Search Tree (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">        _______6______</span><br><span class="line">      /                \</span><br><span class="line">  ___2__             ___8__</span><br><span class="line"> /      \           /      \</span><br><span class="line">0        4         7        9</span><br><span class="line">        /  \</span><br><span class="line">       3   5</span><br><span class="line"></span><br><span class="line">For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> TreeNode <span class="title">lowestCommonAncestor</span><span class="params">(TreeNode root, TreeNode p, TreeNode q)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root.val &gt; p.val &amp;&amp; root.val &gt; q.val) <span class="keyword">return</span> lowestCommonAncestor(root.left, p, q);</span><br><span class="line">    <span class="keyword">if</span> (root.val &lt; p.val &amp;&amp; root.val &lt; q.val) <span class="keyword">return</span> lowestCommonAncestor(root.right, p, q);</span><br><span class="line">    <span class="keyword">return</span> root;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-二叉树的最近公共祖先"><a href="#5-二叉树的最近公共祖先" class="headerlink" title="5. 二叉树的最近公共祖先"></a>5. 二叉树的最近公共祖先</h3><p>236. Lowest Common Ancestor of a Binary Tree (Medium) </p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">       _______3______</span><br><span class="line">      /              \</span><br><span class="line">  ___5__           ___1__</span><br><span class="line"> /      \         /      \</span><br><span class="line">6        2       0        8</span><br><span class="line">        /  \</span><br><span class="line">       7    4</span><br><span class="line"></span><br><span class="line">For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> TreeNode <span class="title">lowestCommonAncestor</span><span class="params">(TreeNode root, TreeNode p, TreeNode q)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span> || root == p || root == q) <span class="keyword">return</span> root;</span><br><span class="line">    TreeNode left = lowestCommonAncestor(root.left, p, q);</span><br><span class="line">    TreeNode right = lowestCommonAncestor(root.right, p, q);</span><br><span class="line">    <span class="keyword">return</span> left == <span class="keyword">null</span> ? right : right == <span class="keyword">null</span> ? left : root;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="6-从有序数组中构造二叉查找树"><a href="#6-从有序数组中构造二叉查找树" class="headerlink" title="6. 从有序数组中构造二叉查找树"></a>6. 从有序数组中构造二叉查找树</h3><p>108. Convert Sorted Array to Binary Search Tree (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/description/">力扣</a></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> TreeNode <span class="title">sortedArrayToBST</span><span class="params">(<span class="keyword">int</span>[] nums)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> toBST(nums, <span class="number">0</span>, nums.length - <span class="number">1</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> TreeNode <span class="title">toBST</span><span class="params">(<span class="keyword">int</span>[] nums, <span class="keyword">int</span> sIdx, <span class="keyword">int</span> eIdx)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (sIdx &gt; eIdx) <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">int</span> mIdx = (sIdx + eIdx) / <span class="number">2</span>;</span><br><span class="line">    TreeNode root = <span class="keyword">new</span> TreeNode(nums[mIdx]);</span><br><span class="line">    root.left =  toBST(nums, sIdx, mIdx - <span class="number">1</span>);</span><br><span class="line">    root.right = toBST(nums, mIdx + <span class="number">1</span>, eIdx);</span><br><span class="line">    <span class="keyword">return</span> root;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="7-根据有序链表构造平衡的二叉查找树"><a href="#7-根据有序链表构造平衡的二叉查找树" class="headerlink" title="7. 根据有序链表构造平衡的二叉查找树"></a>7. 根据有序链表构造平衡的二叉查找树</h3><p>109. Convert Sorted List to Binary Search Tree (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Given the sorted linked list: [-10,-3,0,5,9],</span><br><span class="line"></span><br><span class="line">One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:</span><br><span class="line"></span><br><span class="line">      0</span><br><span class="line">     / \</span><br><span class="line">   -3   9</span><br><span class="line">   /   /</span><br><span class="line"> -10  5</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> TreeNode <span class="title">sortedListToBST</span><span class="params">(ListNode head)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (head == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">if</span> (head.next == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="keyword">new</span> TreeNode(head.val);</span><br><span class="line">    ListNode preMid = preMid(head);</span><br><span class="line">    ListNode mid = preMid.next;</span><br><span class="line">    preMid.next = <span class="keyword">null</span>;  <span class="comment">// 断开链表</span></span><br><span class="line">    TreeNode t = <span class="keyword">new</span> TreeNode(mid.val);</span><br><span class="line">    t.left = sortedListToBST(head);</span><br><span class="line">    t.right = sortedListToBST(mid.next);</span><br><span class="line">    <span class="keyword">return</span> t;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> ListNode <span class="title">preMid</span><span class="params">(ListNode head)</span> </span>&#123;</span><br><span class="line">    ListNode slow = head, fast = head.next;</span><br><span class="line">    ListNode pre = head;</span><br><span class="line">    <span class="keyword">while</span> (fast != <span class="keyword">null</span> &amp;&amp; fast.next != <span class="keyword">null</span>) &#123;</span><br><span class="line">        pre = slow;</span><br><span class="line">        slow = slow.next;</span><br><span class="line">        fast = fast.next.next;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> pre;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="8-在二叉查找树中寻找两个节点，使它们的和为一个给定值"><a href="#8-在二叉查找树中寻找两个节点，使它们的和为一个给定值" class="headerlink" title="8. 在二叉查找树中寻找两个节点，使它们的和为一个给定值"></a>8. 在二叉查找树中寻找两个节点，使它们的和为一个给定值</h3><p>653. Two Sum IV - Input is a BST (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/two-sum-iv-input-is-a-bst/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input:</span><br><span class="line"></span><br><span class="line">    5</span><br><span class="line">   / \</span><br><span class="line">  3   6</span><br><span class="line"> / \   \</span><br><span class="line">2   4   7</span><br><span class="line"></span><br><span class="line">Target = 9</span><br><span class="line"></span><br><span class="line">Output: True</span><br></pre></td></tr></table></figure>

<p>使用中序遍历得到有序数组之后，再利用双指针对数组进行查找。</p>
<p>应该注意到，这一题不能用分别在左右子树两部分来处理这种思想，因为两个待求的节点可能分别在左右子树中。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">findTarget</span><span class="params">(TreeNode root, <span class="keyword">int</span> k)</span> </span>&#123;</span><br><span class="line">    List&lt;Integer&gt; nums = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    inOrder(root, nums);</span><br><span class="line">    <span class="keyword">int</span> i = <span class="number">0</span>, j = nums.size() - <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">while</span> (i &lt; j) &#123;</span><br><span class="line">        <span class="keyword">int</span> sum = nums.get(i) + nums.get(j);</span><br><span class="line">        <span class="keyword">if</span> (sum == k) <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        <span class="keyword">if</span> (sum &lt; k) i++;</span><br><span class="line">        <span class="keyword">else</span> j--;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">inOrder</span><span class="params">(TreeNode root, List&lt;Integer&gt; nums)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) <span class="keyword">return</span>;</span><br><span class="line">    inOrder(root.left, nums);</span><br><span class="line">    nums.add(root.val);</span><br><span class="line">    inOrder(root.right, nums);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="9-在二叉查找树中查找两个节点之差的最小绝对值"><a href="#9-在二叉查找树中查找两个节点之差的最小绝对值" class="headerlink" title="9. 在二叉查找树中查找两个节点之差的最小绝对值"></a>9. 在二叉查找树中查找两个节点之差的最小绝对值</h3><p>530. Minimum Absolute Difference in BST (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input:</span><br><span class="line"></span><br><span class="line">   1</span><br><span class="line">    \</span><br><span class="line">     3</span><br><span class="line">    /</span><br><span class="line">   2</span><br><span class="line"></span><br><span class="line">Output:</span><br><span class="line"></span><br><span class="line">1</span><br></pre></td></tr></table></figure>

<p>利用二叉查找树的中序遍历为有序的性质，计算中序遍历中临近的两个节点之差的绝对值，取最小值。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> minDiff = Integer.MAX_VALUE;</span><br><span class="line"><span class="keyword">private</span> TreeNode preNode = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getMinimumDifference</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    inOrder(root);</span><br><span class="line">    <span class="keyword">return</span> minDiff;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">inOrder</span><span class="params">(TreeNode node)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (node == <span class="keyword">null</span>) <span class="keyword">return</span>;</span><br><span class="line">    inOrder(node.left);</span><br><span class="line">    <span class="keyword">if</span> (preNode != <span class="keyword">null</span>) minDiff = Math.min(minDiff, node.val - preNode.val);</span><br><span class="line">    preNode = node;</span><br><span class="line">    inOrder(node.right);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="10-寻找二叉查找树中出现次数最多的值"><a href="#10-寻找二叉查找树中出现次数最多的值" class="headerlink" title="10. 寻找二叉查找树中出现次数最多的值"></a>10. 寻找二叉查找树中出现次数最多的值</h3><p>501. Find Mode in Binary Search Tree (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/find-mode-in-binary-search-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">   1</span><br><span class="line">    \</span><br><span class="line">     2</span><br><span class="line">    /</span><br><span class="line">   2</span><br><span class="line"></span><br><span class="line">return [2].</span><br></pre></td></tr></table></figure>

<p>答案可能不止一个，也就是有多个值出现的次数一样多。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> curCnt = <span class="number">1</span>;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> maxCnt = <span class="number">1</span>;</span><br><span class="line"><span class="keyword">private</span> TreeNode preNode = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">int</span>[] findMode(TreeNode root) &#123;</span><br><span class="line">    List&lt;Integer&gt; maxCntNums = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    inOrder(root, maxCntNums);</span><br><span class="line">    <span class="keyword">int</span>[] ret = <span class="keyword">new</span> <span class="keyword">int</span>[maxCntNums.size()];</span><br><span class="line">    <span class="keyword">int</span> idx = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> num : maxCntNums) &#123;</span><br><span class="line">        ret[idx++] = num;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">inOrder</span><span class="params">(TreeNode node, List&lt;Integer&gt; nums)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (node == <span class="keyword">null</span>) <span class="keyword">return</span>;</span><br><span class="line">    inOrder(node.left, nums);</span><br><span class="line">    <span class="keyword">if</span> (preNode != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (preNode.val == node.val) curCnt++;</span><br><span class="line">        <span class="keyword">else</span> curCnt = <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (curCnt &gt; maxCnt) &#123;</span><br><span class="line">        maxCnt = curCnt;</span><br><span class="line">        nums.clear();</span><br><span class="line">        nums.add(node.val);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (curCnt == maxCnt) &#123;</span><br><span class="line">        nums.add(node.val);</span><br><span class="line">    &#125;</span><br><span class="line">    preNode = node;</span><br><span class="line">    inOrder(node.right, nums);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="Trie"><a href="#Trie" class="headerlink" title="Trie"></a>Trie</h2><div align="center"> <img src= "" data-lazy-src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/5c638d59-d4ae-4ba4-ad44-80bdc30f38dd.jpg"/> </div><br>

<p>Trie，又称前缀树或字典树，用于判断字符串是否存在或者是否具有某种字符串前缀。</p>
<h3 id="1-实现一个-Trie"><a href="#1-实现一个-Trie" class="headerlink" title="1. 实现一个 Trie"></a>1. 实现一个 Trie</h3><p>208. Implement Trie (Prefix Tree) (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/implement-trie-prefix-tree/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/implement-trie-prefix-tree/description/">力扣</a></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Trie</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123;</span><br><span class="line">        Node[] childs = <span class="keyword">new</span> Node[<span class="number">26</span>];</span><br><span class="line">        <span class="keyword">boolean</span> isLeaf;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Node root = <span class="keyword">new</span> Node();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Trie</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">insert</span><span class="params">(String word)</span> </span>&#123;</span><br><span class="line">        insert(word, root);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">insert</span><span class="params">(String word, Node node)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (node == <span class="keyword">null</span>) <span class="keyword">return</span>;</span><br><span class="line">        <span class="keyword">if</span> (word.length() == <span class="number">0</span>) &#123;</span><br><span class="line">            node.isLeaf = <span class="keyword">true</span>;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">int</span> index = indexForChar(word.charAt(<span class="number">0</span>));</span><br><span class="line">        <span class="keyword">if</span> (node.childs[index] == <span class="keyword">null</span>) &#123;</span><br><span class="line">            node.childs[index] = <span class="keyword">new</span> Node();</span><br><span class="line">        &#125;</span><br><span class="line">        insert(word.substring(<span class="number">1</span>), node.childs[index]);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">search</span><span class="params">(String word)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> search(word, root);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">search</span><span class="params">(String word, Node node)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (node == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        <span class="keyword">if</span> (word.length() == <span class="number">0</span>) <span class="keyword">return</span> node.isLeaf;</span><br><span class="line">        <span class="keyword">int</span> index = indexForChar(word.charAt(<span class="number">0</span>));</span><br><span class="line">        <span class="keyword">return</span> search(word.substring(<span class="number">1</span>), node.childs[index]);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">startsWith</span><span class="params">(String prefix)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> startWith(prefix, root);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">startWith</span><span class="params">(String prefix, Node node)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (node == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        <span class="keyword">if</span> (prefix.length() == <span class="number">0</span>) <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        <span class="keyword">int</span> index = indexForChar(prefix.charAt(<span class="number">0</span>));</span><br><span class="line">        <span class="keyword">return</span> startWith(prefix.substring(<span class="number">1</span>), node.childs[index]);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">indexForChar</span><span class="params">(<span class="keyword">char</span> c)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> c - <span class="string">&#x27;a&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="2-实现一个-Trie，用来求前缀和"><a href="#2-实现一个-Trie，用来求前缀和" class="headerlink" title="2. 实现一个 Trie，用来求前缀和"></a>2. 实现一个 Trie，用来求前缀和</h3><p>677. Map Sum Pairs (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/map-sum-pairs/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/map-sum-pairs/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input: insert(&quot;apple&quot;, 3), Output: Null</span><br><span class="line">Input: sum(&quot;ap&quot;), Output: 3</span><br><span class="line">Input: insert(&quot;app&quot;, 2), Output: Null</span><br><span class="line">Input: sum(&quot;ap&quot;), Output: 5</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MapSum</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123;</span><br><span class="line">        Node[] child = <span class="keyword">new</span> Node[<span class="number">26</span>];</span><br><span class="line">        <span class="keyword">int</span> value;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Node root = <span class="keyword">new</span> Node();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MapSum</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">insert</span><span class="params">(String key, <span class="keyword">int</span> val)</span> </span>&#123;</span><br><span class="line">        insert(key, root, val);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">insert</span><span class="params">(String key, Node node, <span class="keyword">int</span> val)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (node == <span class="keyword">null</span>) <span class="keyword">return</span>;</span><br><span class="line">        <span class="keyword">if</span> (key.length() == <span class="number">0</span>) &#123;</span><br><span class="line">            node.value = val;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">int</span> index = indexForChar(key.charAt(<span class="number">0</span>));</span><br><span class="line">        <span class="keyword">if</span> (node.child[index] == <span class="keyword">null</span>) &#123;</span><br><span class="line">            node.child[index] = <span class="keyword">new</span> Node();</span><br><span class="line">        &#125;</span><br><span class="line">        insert(key.substring(<span class="number">1</span>), node.child[index], val);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">sum</span><span class="params">(String prefix)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> sum(prefix, root);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">sum</span><span class="params">(String prefix, Node node)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (node == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">if</span> (prefix.length() != <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">int</span> index = indexForChar(prefix.charAt(<span class="number">0</span>));</span><br><span class="line">            <span class="keyword">return</span> sum(prefix.substring(<span class="number">1</span>), node.child[index]);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">int</span> sum = node.value;</span><br><span class="line">        <span class="keyword">for</span> (Node child : node.child) &#123;</span><br><span class="line">            sum += sum(prefix, child);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sum;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">indexForChar</span><span class="params">(<span class="keyword">char</span> c)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> c - <span class="string">&#x27;a&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Zhang Shuo</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E6%A0%91/">https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E6%A0%91/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://zhang-shuo-fr.gitee.io/hexo3" target="_blank">Zhang Shuo'blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/hexo3/tags/Leetcode%E9%A2%98%E8%A7%A3/">Leetcode题解</a></div><div class="post_share"><div class="social-share" data-image="/hexo3/img/13.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/hexo3/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/hexo3/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/hexo3/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/hexo3/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/hexo3/2021/12/06/notes/SQL%20%E7%BB%83%E4%B9%A0/"><img class="prev-cover" src= "" data-lazy-src="/hexo3/img/13.jpg" onerror="onerror=null;src='/hexo3/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">SQL练习</div></div></a></div><div class="next-post pull-right"><a href="/hexo3/2021/12/06/notes/Java%20IO/"><img class="next-cover" src= "" data-lazy-src="/hexo3/img/1.jpg" onerror="onerror=null;src='/hexo3/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Java IO</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE/" title="Leetcode 题解 - 二分查找"><img class="cover" src= "" data-lazy-src="/hexo3/img/1.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 二分查找</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E4%BD%8D%E8%BF%90%E7%AE%97/" title="Leetcode 题解 - 位运算"><img class="cover" src= "" data-lazy-src="/hexo3/img/18.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 位运算</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%88%86%E6%B2%BB/" title="Leetcode 题解 - 分治"><img class="cover" src= "" data-lazy-src="/hexo3/img/8.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 分治</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%8F%8C%E6%8C%87%E9%92%88/" title="Leetcode 题解 - 双指针"><img class="cover" src= "" data-lazy-src="/hexo3/img/1.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 双指针</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%93%88%E5%B8%8C%E8%A1%A8/" title="Leetcode 题解 - 哈希表"><img class="cover" src= "" data-lazy-src="/hexo3/img/12.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 哈希表</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%9B%BE/" title="Leetcode 题解 - 图"><img class="cover" src= "" data-lazy-src="/hexo3/img/19.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 图</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Leetcode-%E9%A2%98%E8%A7%A3-%E6%A0%91"><span class="toc-number">1.</span> <span class="toc-text">Leetcode 题解 - 树</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%80%92%E5%BD%92"><span class="toc-number">1.1.</span> <span class="toc-text">递归</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E6%A0%91%E7%9A%84%E9%AB%98%E5%BA%A6"><span class="toc-number">1.1.1.</span> <span class="toc-text">1. 树的高度</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%B9%B3%E8%A1%A1%E6%A0%91"><span class="toc-number">1.1.2.</span> <span class="toc-text">2. 平衡树</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E4%B8%A4%E8%8A%82%E7%82%B9%E7%9A%84%E6%9C%80%E9%95%BF%E8%B7%AF%E5%BE%84"><span class="toc-number">1.1.3.</span> <span class="toc-text">3. 两节点的最长路径</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E7%BF%BB%E8%BD%AC%E6%A0%91"><span class="toc-number">1.1.4.</span> <span class="toc-text">4. 翻转树</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E5%BD%92%E5%B9%B6%E4%B8%A4%E6%A3%B5%E6%A0%91"><span class="toc-number">1.1.5.</span> <span class="toc-text">5. 归并两棵树</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-%E5%88%A4%E6%96%AD%E8%B7%AF%E5%BE%84%E5%92%8C%E6%98%AF%E5%90%A6%E7%AD%89%E4%BA%8E%E4%B8%80%E4%B8%AA%E6%95%B0"><span class="toc-number">1.1.6.</span> <span class="toc-text">6. 判断路径和是否等于一个数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-%E7%BB%9F%E8%AE%A1%E8%B7%AF%E5%BE%84%E5%92%8C%E7%AD%89%E4%BA%8E%E4%B8%80%E4%B8%AA%E6%95%B0%E7%9A%84%E8%B7%AF%E5%BE%84%E6%95%B0%E9%87%8F"><span class="toc-number">1.1.7.</span> <span class="toc-text">7. 统计路径和等于一个数的路径数量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-%E5%AD%90%E6%A0%91"><span class="toc-number">1.1.8.</span> <span class="toc-text">8. 子树</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-%E6%A0%91%E7%9A%84%E5%AF%B9%E7%A7%B0"><span class="toc-number">1.1.9.</span> <span class="toc-text">9. 树的对称</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#10-%E6%9C%80%E5%B0%8F%E8%B7%AF%E5%BE%84"><span class="toc-number">1.1.10.</span> <span class="toc-text">10. 最小路径</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#11-%E7%BB%9F%E8%AE%A1%E5%B7%A6%E5%8F%B6%E5%AD%90%E8%8A%82%E7%82%B9%E7%9A%84%E5%92%8C"><span class="toc-number">1.1.11.</span> <span class="toc-text">11. 统计左叶子节点的和</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#12-%E7%9B%B8%E5%90%8C%E8%8A%82%E7%82%B9%E5%80%BC%E7%9A%84%E6%9C%80%E5%A4%A7%E8%B7%AF%E5%BE%84%E9%95%BF%E5%BA%A6"><span class="toc-number">1.1.12.</span> <span class="toc-text">12. 相同节点值的最大路径长度</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#13-%E9%97%B4%E9%9A%94%E9%81%8D%E5%8E%86"><span class="toc-number">1.1.13.</span> <span class="toc-text">13. 间隔遍历</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#14-%E6%89%BE%E5%87%BA%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%AD%E7%AC%AC%E4%BA%8C%E5%B0%8F%E7%9A%84%E8%8A%82%E7%82%B9"><span class="toc-number">1.1.14.</span> <span class="toc-text">14. 找出二叉树中第二小的节点</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B1%82%E6%AC%A1%E9%81%8D%E5%8E%86"><span class="toc-number">1.2.</span> <span class="toc-text">层次遍历</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E4%B8%80%E6%A3%B5%E6%A0%91%E6%AF%8F%E5%B1%82%E8%8A%82%E7%82%B9%E7%9A%84%E5%B9%B3%E5%9D%87%E6%95%B0"><span class="toc-number">1.2.1.</span> <span class="toc-text">1. 一棵树每层节点的平均数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%BE%97%E5%88%B0%E5%B7%A6%E4%B8%8B%E8%A7%92%E7%9A%84%E8%8A%82%E7%82%B9"><span class="toc-number">1.2.2.</span> <span class="toc-text">2. 得到左下角的节点</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E4%B8%AD%E5%90%8E%E5%BA%8F%E9%81%8D%E5%8E%86"><span class="toc-number">1.3.</span> <span class="toc-text">前中后序遍历</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E9%9D%9E%E9%80%92%E5%BD%92%E5%AE%9E%E7%8E%B0%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%89%8D%E5%BA%8F%E9%81%8D%E5%8E%86"><span class="toc-number">1.3.1.</span> <span class="toc-text">1. 非递归实现二叉树的前序遍历</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E9%9D%9E%E9%80%92%E5%BD%92%E5%AE%9E%E7%8E%B0%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%90%8E%E5%BA%8F%E9%81%8D%E5%8E%86"><span class="toc-number">1.3.2.</span> <span class="toc-text">2. 非递归实现二叉树的后序遍历</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E9%9D%9E%E9%80%92%E5%BD%92%E5%AE%9E%E7%8E%B0%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E4%B8%AD%E5%BA%8F%E9%81%8D%E5%8E%86"><span class="toc-number">1.3.3.</span> <span class="toc-text">3. 非递归实现二叉树的中序遍历</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#BST"><span class="toc-number">1.4.</span> <span class="toc-text">BST</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E4%BF%AE%E5%89%AA%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91"><span class="toc-number">1.4.1.</span> <span class="toc-text">1. 修剪二叉查找树</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%AF%BB%E6%89%BE%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91%E7%9A%84%E7%AC%AC-k-%E4%B8%AA%E5%85%83%E7%B4%A0"><span class="toc-number">1.4.2.</span> <span class="toc-text">2. 寻找二叉查找树的第 k 个元素</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E6%8A%8A%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91%E6%AF%8F%E4%B8%AA%E8%8A%82%E7%82%B9%E7%9A%84%E5%80%BC%E9%83%BD%E5%8A%A0%E4%B8%8A%E6%AF%94%E5%AE%83%E5%A4%A7%E7%9A%84%E8%8A%82%E7%82%B9%E7%9A%84%E5%80%BC"><span class="toc-number">1.4.3.</span> <span class="toc-text">3. 把二叉查找树每个节点的值都加上比它大的节点的值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91%E7%9A%84%E6%9C%80%E8%BF%91%E5%85%AC%E5%85%B1%E7%A5%96%E5%85%88"><span class="toc-number">1.4.4.</span> <span class="toc-text">4. 二叉查找树的最近公共祖先</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E8%BF%91%E5%85%AC%E5%85%B1%E7%A5%96%E5%85%88"><span class="toc-number">1.4.5.</span> <span class="toc-text">5. 二叉树的最近公共祖先</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-%E4%BB%8E%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84%E4%B8%AD%E6%9E%84%E9%80%A0%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91"><span class="toc-number">1.4.6.</span> <span class="toc-text">6. 从有序数组中构造二叉查找树</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-%E6%A0%B9%E6%8D%AE%E6%9C%89%E5%BA%8F%E9%93%BE%E8%A1%A8%E6%9E%84%E9%80%A0%E5%B9%B3%E8%A1%A1%E7%9A%84%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91"><span class="toc-number">1.4.7.</span> <span class="toc-text">7. 根据有序链表构造平衡的二叉查找树</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-%E5%9C%A8%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91%E4%B8%AD%E5%AF%BB%E6%89%BE%E4%B8%A4%E4%B8%AA%E8%8A%82%E7%82%B9%EF%BC%8C%E4%BD%BF%E5%AE%83%E4%BB%AC%E7%9A%84%E5%92%8C%E4%B8%BA%E4%B8%80%E4%B8%AA%E7%BB%99%E5%AE%9A%E5%80%BC"><span class="toc-number">1.4.8.</span> <span class="toc-text">8. 在二叉查找树中寻找两个节点，使它们的和为一个给定值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-%E5%9C%A8%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91%E4%B8%AD%E6%9F%A5%E6%89%BE%E4%B8%A4%E4%B8%AA%E8%8A%82%E7%82%B9%E4%B9%8B%E5%B7%AE%E7%9A%84%E6%9C%80%E5%B0%8F%E7%BB%9D%E5%AF%B9%E5%80%BC"><span class="toc-number">1.4.9.</span> <span class="toc-text">9. 在二叉查找树中查找两个节点之差的最小绝对值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#10-%E5%AF%BB%E6%89%BE%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91%E4%B8%AD%E5%87%BA%E7%8E%B0%E6%AC%A1%E6%95%B0%E6%9C%80%E5%A4%9A%E7%9A%84%E5%80%BC"><span class="toc-number">1.4.10.</span> <span class="toc-text">10. 寻找二叉查找树中出现次数最多的值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Trie"><span class="toc-number">1.5.</span> <span class="toc-text">Trie</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA-Trie"><span class="toc-number">1.5.1.</span> <span class="toc-text">1. 实现一个 Trie</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA-Trie%EF%BC%8C%E7%94%A8%E6%9D%A5%E6%B1%82%E5%89%8D%E7%BC%80%E5%92%8C"><span class="toc-number">1.5.2.</span> <span class="toc-text">2. 实现一个 Trie，用来求前缀和</span></a></li></ol></li></ol></li></ol></div></div></div></div></main><footer id="footer" style="background-image: url('/hexo3/img/13.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By Zhang Shuo</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcome to my blog!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">簡</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/hexo3/js/utils.js"></script><script src="/hexo3/js/main.js"></script><script src="/hexo3/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/hexo3/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><div class="aplayer no-destroy" data-id="000PeZCQ1i4XVs" data-server="tencent" data-type="artist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="none" data-autoplay="true" muted></div><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="true"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>